package com.mnkjxy.beauty.net;

import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mnkjxy.beauty.net.protocal.FileUploadBasic;
import com.mnkjxy.beauty.values.Constant;

/**
 * 跟服务器执行请求的http工具类
 * 
 * @author lqp
 * 
 */
public class HttpClientUtils {

	protected static final String TAG = "HttpClientUtils";

	/**
	 * 向服务器发送一段xml数据,必须在子线程中调用
	 * 
	 * @param uri
	 *            服务器地址
	 * @param xml
	 *            xml数据
	 * @return 服务器返回的输入流
	 */
	public static InputStream sendXml(String uri, String xml) {
		HttpClient client = new DefaultHttpClient();

		HttpPost post = new HttpPost(uri);
		try {
			StringEntity entity = new StringEntity(xml, Constant.CHARSET);

			post.setEntity(entity);
			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == 200) {
				return response.getEntity().getContent();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 此方法运可以在ui线程中调用
	 * 
	 * @param url
	 *            服务器地址
	 * @param fileUpload
	 *            具体发送的请求
	 * @param callBack
	 *            回调,根据具体情况复写
	 */
	public static void sendImage(String url, FileUploadBasic fileUpload, RequestCallBack<Object> callBack) {

		RequestParams params = new RequestParams("utf-8");

		params.addQueryStringParameter("text", fileUpload.getText());
		params.addQueryStringParameter("requestType", fileUpload.getRequestType());
		params.addQueryStringParameter("username", fileUpload.getUserName());
		params.addQueryStringParameter("fileName", fileUpload.getFileName());

		params.setBodyEntity(new FileEntity(fileUpload.getFile(), "image/*"));

		HttpUtils utils = new HttpUtils();

		utils.send(HttpMethod.POST, url, params, callBack);

	}

}
